package com.example.baimao_tp.data

import android.content.Context
import android.util.Log
import com.example.baimao_tp.R
import com.example.baimao_tp.data.model.PoseConfig
import com.example.baimao_tp.data.model.PoseItem
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object PoseConfigManager {
    private const val TAG = "PoseConfigManager"
    private var poseConfig: PoseConfig? = null

    /**
     * 从YAML文件加载姿势配置
     */
    suspend fun loadPoseConfig(context: Context): Result<List<PoseItem>> = withContext(Dispatchers.IO) {
        return@withContext try {
            Log.d(TAG, "开始加载姿势配置文件")

            // 从raw资源读取YAML文件
            val inputStream = context.resources.openRawResource(R.raw.pose_config)
            val yamlContent = inputStream.bufferedReader().use { it.readText() }

            Log.d(TAG, "YAML文件内容长度: ${yamlContent.length}")

            // 解析YAML
            val mapper = ObjectMapper(YAMLFactory())
            poseConfig = mapper.readValue(yamlContent, PoseConfig::class.java)

            Log.d(TAG, "姿势配置加载成功，姿势数量: ${poseConfig?.pose?.size}")
            poseConfig?.pose?.forEach { pose ->
                Log.d(TAG, "姿势配置: value=${pose.value}, en=${pose.en}, cn=${pose.cn}")
            }

            Result.success(poseConfig?.pose ?: emptyList())
        } catch (e: Exception) {
            Log.e(TAG, "加载姿势配置失败", e)
            Result.failure(e)
        }
    }

    /**
     * 根据语言获取姿势列表
     */
    suspend fun getPosesForLanguage(context: Context, language: String = "zh"): Result<List<PoseItem>> {
        return if (poseConfig == null) {
            loadPoseConfig(context)
        } else {
            Result.success(poseConfig!!.pose)
        }
    }

    /**
     * 根据value获取姿势
     */
    fun getPoseByValue(value: String): PoseItem? {
        return poseConfig?.pose?.find { it.value == value }
    }

    /**
     * 获取所有姿势的value列表（用于tags拼接）
     */
    fun getAllPoseValues(): List<String> {
        return poseConfig?.pose?.map { it.value } ?: emptyList()
    }

    /**
     * 检查是否已加载配置
     */
    fun isConfigLoaded(): Boolean {
        return poseConfig != null
    }

    /**
     * 重置配置（用于测试）
     */
    fun resetConfig() {
        poseConfig = null
    }
}